<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" :rules="rules" class="formInline" ref="formInline"
            label-width="76px" slot="form">
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="姓名">
                            <el-input v-model="formInline.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="8">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="formInline.phone" placeholder="请输入手机号" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="8">
                        <el-form-item label="e学云ID号"  prop="exueCode">
                            <el-input v-model="formInline.exueCode" placeholder="请输入e学云ID号" :maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                 </el-row>
                    <div class="top-line">
                        <el-button type="primary" @click="search('formInline')">查询</el-button>
                    </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="showAddTea">添加教师</el-button>
                    <el-button @click="showLotImport">批量导入</el-button>
                    <el-button @click="deleteRoleLots">批量删除</el-button>
                </div>
            </div>
            <el-table :data="AnnounceList" border style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTable" v-loading="loading">
                <el-table-column type="selection" align='center' width="55"></el-table-column>
                <el-table-column label="e学云ID号" align='center'>
                    <template scope="scope">
                        {{scope.row.exueCode ? scope.row.exueCode : '--'}}
                    </template>
                </el-table-column>
                <el-table-column label="姓名" align='center'>
                     <template scope="scope">
                        {{scope.row.name ? scope.row.name : '--'}}
                    </template>
                </el-table-column>
                <el-table-column label="注册手机号" align='center'>
                     <template scope="scope">
                        {{scope.row.phone ? scope.row.phone : '--'}}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间"  align='center' min-width="140px">
                    <template scope="scope">
                        {{scope.row.createTime?scope.row.createTime:'--'}}
                    </template>
                </el-table-column>
                <el-table-column label="最后登录时间"  align='center'  min-width="140px">
                    <template scope="scope">
                        {{scope.row.lastLoginTime?scope.row.lastLoginTime:'--'}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="190" align='left'>
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="goToCorrect(scope.row.teacherId)">修改</el-button>
                        <el-button type="text" class="btn-success" @click="deleteListOne(scope.row.teacherId)">删除</el-button>
                        <el-button type="text" class="btn-success" @click="teacherClass(scope.row.teacherId)">任教班级</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <addTeaDialog :addTeaData="addTeaData" @search-list="search('formInline')"> </addTeaDialog>
        <importLotDialog :addImportData="addImportData"  @importProgress="importProgress"> </importLotDialog>
        <!-- created by cuihd at 20180713 优化批量删除教师 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
import { getTeachersByPage, batchDeleteTeacher, getSchoolTypeById, batchDeleteTeacherProgress, batchImportForTeacherProgress} from 'api/teacherManage';
import TableLayout from 'components/TableLayout';
import addTeaDialog from './addTea';
import importLotDialog from './importLot';
import { mapState, mapActions, mapGetters } from 'vuex';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from 'components/SchoolClasss/school';
import validate from '@/utils/validate';
export default {
    name: 'teacherManagesList',
    components: { TableLayout, addTeaDialog, importLotDialog, province, city, region, school},
    data() {
        return {
            loading: true,
            schoolType: null,
            formInline: { // 查询 表单数据
                fProvinceId: '', // 省份
                fCityId: '', // 市区
                fAreaId: '', // 区县
                schoolName: '', // 学校名字
                workId: '', // 职务
                subjectName: '', // 学科
                loginNum: '',
                areaId: '', // 
                name: '',
                phone: '',
                exueCode: '',
                schoolId: '',
                schoolNameList: [] // 学校名称列表
            },
            // 教职工类型 教职工1,非教职工0
            workTypeArr: [{
                workTypeName: '教职工',
                workTypeId: '1'
            }, {
                workTypeName: '非教职工',
                workTypeId: '0'
            }],
            checked: true,
            AnnounceList: [],
            dataNum: 1, // 表格1显示条数，初始为1
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            addTeaData: {
                dialogAddTea: false
            },
            addImportData: {
                dialogLotImport: false
            },
            dialog: {
                dialogFormVisible: false
            },
            dataForm: {
            },
            multipleSelection: [], // 勾选的表格的项目
        
            schoolLoading: false,
            subjectLoading: false,
            rules: {
                exueCode: [...validate.exueCode()],
                phone: [...validate.phone()]
            },
            /**
             * created by cuihd at 20180713
             * 优化批量删除教师
             * 添加相关变量
             */
            dialogTitle: '正在批量删除教师...',
            dialogTimeout: false,
            progress: 0
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表

        }),
        ...mapGetters([
            'uid',
            'schoolId',
            'schoolName'
        ])
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        }
    },
    // 初始化
    created() {
        this.searchFetchData();
        this.getSchoolTypeById();
    },
    methods: {
        // 全局获取行数classStudent
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        teacherClass(teacherId) {
            let schoolType=this.schoolType;
            this.$router.push({ path: `/teacherManage/teacherClass/${teacherId}/${schoolType}` });
        },
        // created by cuihd at 20180711
        // 轮询接口获取未导入的数量
        batchImportProgress(obj) { // 递归轮询
            let totalNum = Number(obj.totalNum); // 强转成number类型
            batchImportForTeacherProgress(obj.timeStamp, obj.schoolId).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchImportProgress(obj);
                        }, 1000);
                    } else {
                        this.dialogTitle = '批量导入教师成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.searchFetchData();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量导入失败！',
                        type: 'error'
                    });
                    this.searchFetchData();
                }          
            }).catch(err => {
                console.log(err);
            })
        },
        // 唤出批量导入进度条（和批量删除共用一个）
        importProgress(val) {
            this.dialogTitle = '正在批量导入教师中...'; // 设置进度条的title
            this.dialogTimeout = true;
            this.progress = 0; // 初始化进度条
            this.batchImportProgress(val);
        },
        // 展示添加教师弹窗
        showAddTea() {
            this.addTeaData.dialogAddTea = true;
        },
        showLotImport() {
            this.addImportData.dialogLotImport = true;
        },
        // 点击查询 
        search(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.listQuery.page = 1;
                    this.loading = true;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });
        },

        getSchoolTypeById() {
            getSchoolTypeById(this.schoolId).then(res => {
                this.schoolType=res.data.content.sType;
            });
        },
        // 查询列表
        searchFetchData() {
            let curPage = this.listQuery.page;
            let pageSize = this.config.pageSize;
            let schoolId = this.schoolId// 学校id
            let subjectId = this.formInline.subjectName;
            let name = this.formInline.name;
            let phone = this.formInline.phone;
            let exueCode = this.formInline.exueCode;// e学云ID号
            this.loading = true;
            getTeachersByPage(curPage, pageSize, schoolId, subjectId, name, phone, exueCode).then(res => {
                this.loading = false;
                this.AnnounceList = res.data.content.list;
                this.listQuery.total = res.data.content.pagination.total;
            }).catch(() => {
                this.loading = false;
            });
        },
        // 跳转到 修改页面
        goToCorrect(teacherId) {
            let schoolType=this.schoolType;
            this.$router.push({ path: `correct/${teacherId}/${schoolType}` });
        },
        // 单个删除
        deleteListOne(teacherIds) {
            this.$confirm('确定删除该教师？', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                let schoolId=this.schoolId;
                this.loading = true;
                batchDeleteTeacher(schoolId, teacherIds).then(res => {                                     
                    // this.searchFetchData();  
                    setTimeout(() => {
                        this.searchFetchData();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }, 2500); // 后端教师异步删除，前端无奈做出改变，后期继续优化               
                }).catch(() => {
                    this.loading = false;
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 批量删除教师信息  传老师id数组
        deleteRoleLots() {
            let teacherIds = '';
            for (let i = 0; i < this.multipleSelection.length; i++) {
                teacherIds += this.multipleSelection[i].teacherId + ',';
            }
            teacherIds = teacherIds.substring(0, teacherIds.length - 1)
            if (teacherIds.length == 0) {
                this.$message({
                    type: 'info',
                    message: '请选择要删除的教师!'
                });
                return;
            }
            this.$confirm('将删除选中教师, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                let schoolId=this.schoolId;
                this.loading = true;
                batchDeleteTeacher(schoolId, teacherIds).then(res => {
                    /**
                     * created by cuihd at 20180709
                     * 优化批量删除教师
                     * 添加相关变量
                     */
                    if (res.data.content) {
                        let timeStamp = res.data.content.timeStamp;
                        let totalNum = res.data.content.totalNum;
                        this.dialogTitle = '正在批量删除教师...';
                        this.dialogTimeout = true;
                        this.batchProgress(timeStamp, totalNum);
                    }                   
                }).catch(() => {
                    this.loading = false;
                });
            }).catch(() => {
                // console.log(1);
            });
        },
        // created by cuihd at 20180712
        // 轮询接口获取未处理的数量
        batchProgress(timeStamp, totalNum) { // 递归轮询batchDeleteTeacherProgress接口
            totalNum = Number(totalNum); // 强转成number类型
            batchDeleteTeacherProgress(timeStamp).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchProgress(timeStamp, totalNum);
                        }, 1500);
                    } else {
                        this.dialogTitle = '批量删除教师成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.searchFetchData();
                        }, 1000)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量删除失败！',
                        type: 'error'
                    });
                    this.searchFetchData();
                }
            }).catch(err => {
                console.log(err);
            })
        },
        // 分页
        handleSizeChange(val) {
            this.loading = true;
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        }
    }
}
</script>
<style lang="scss">
@import '../../../styles/var';
.content {
    position: relative;
    padding: 0px;
    $bgcolor: #fff;
    .formInline {
        .formBtn {
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition {
                position: absolute;
                right: 0px;
                top: 18px;
            }
        }
    }
}
</style>